import React from 'react'

// 导入组件
import { WingBlank,Grid,Flex,Carousel} from 'antd-mobile';

// 导入axios
import axios from 'axios'
import {BASE_URL} from '../../utils/url'

// 导入导航菜单图片
import Nav1 from '../../assets/images/nav-1.png'
import Nav2 from '../../assets/images/nav-2.png'
import Nav3 from '../../assets/images/nav-3.png'
import Nav4 from '../../assets/images/nav-4.png'

// 导入样式文件
import './index.css'

// 导入获取数据方法
// import {getCurrentCity} from '../../utils'

// 导航菜单属性
const navs = [
    {
        id: 1,
        img: Nav1,
        title: '整租',
        path: '/home/list'
    },
    {
        id: 2,
        img: Nav2,
        title: '合租',
        path: '/home/list'
    },
    {
        id: 3,
        img: Nav3,
        title: '地图找房',
        path: '/map'
    },
    {
        id: 3,
        img: Nav4,
        title: '去出租',
        path: '/rent'
    },
]

const data = Array.from(new Array(4)).map((_val, i) => ({
  icon: 'https://gw.alipayobjects.com/zos/rmsportal/nywPmnTAvTmLusPxHPSu.png',
  text: `name${i}`,
}));

// 获取地理位置信息
// navigator.geolocation.getCurrentPosition(position => {
//   console.log('当前位置信息',position);
// })

/*
  1、打开百度地图JS API定位文档
  2、通过IP定位获取当前城市名称
  3、调用我们服务器接口，换取项目中的城市信息(有房源的城市名称和Id)
  4、将接口返回的城市信息展示在顶部导航栏中
*/

export default class Index extends React.Component {
    state = {
        // 轮播图状态数据
        swipers:[],
        // isSwiperLoaded:false
        // 租房小组数据
        groups:[],
        // 最新资讯
        news:[],
        curCityName:''
    }

    /*
    轮播图存在的两个问题：
    1、不会自动播放
    2、从其它路由返回时，高度不够

    原因：轮播图数据是动态加载的，加载完成前后数量不一致
    解决？
    1、在state中添加表示轮播图加载完成的数据
    2、在轮播图数据加载完成时，修改数据状态值为true
    3、只有在轮播图数据加载完成的情况下，才渲染轮播图组件
*/

    // 获取轮播图数据
    async getSwipers() {
        const res = await axios.get('http://localhost:3000/home/swiper')
        this.setState({
            swipers:res.data.body,
            // isSwiperLoaded:true
        })
    }

    // 获取租房小组数据
    async getGroups() {
      const res = await axios.get('http://localhost:3000/home/groups',{
        params:{
          area:'area=AREA%7c88cff55c-aaa4-e2e0'
        }
      })
      this.setState({
        groups: res.data.body
      })
    }

    // 获取最新咨询
    async getNews() {
      const res = await axios.get('http://localhost:3000/home/news')
      this.setState({
        news:res.data.body
      })
    }

    async componentDidMount() {
        this.getSwipers()
        this.getGroups()
        this.getNews()

        // const curCity = await getCurrentCity()
        // this.setState({
        //   curCityName:curCity.label
        // })
        // 通过IP定位获取当前城市名称
      // const curCity = new window.BMapGL.localCity()
      // curCity.get(async res => {
      //   // console.log('当前城市信息',res);
      //   const result = await axios.get(`http://localhost:3000/area/info?name=${res.name}`)
      //   this.setState({
      //     curCityName:result.data.body.label
      //   })
      // })
    }

    // 渲染轮播图结构 
    renderSwipers() {
        return 
        this.state.swipers.map(item => (
            <a
              key={item.id}
              href="http://www.alipay.com"
              style={{ 
                  display: 'inline-block', 
                  width: '100%', 
                  height: this.state.imgHeight 
              }}
            >
              <img
                src={`http://localhost:3000${item.imgSrc}`}
                alt=""
                style={{ width: '100%', verticalAlign: 'top' }}
              />
            </a>
        ))
    }

    // 渲染导航菜单
    renderNavs() {
        return navs.map(item =>
            <Flex.Item key={item.title} onClick={() =>
            this.props.history.push(item.path)}>
                <img src={item.img} alt="" />
                <h2>{item.title}</h2>
            </Flex.Item>
        )
    }

    // 渲染最新咨询
    renderNews() {
      return this.state.news.map((item) =>(
        <div className="news-item" key="item.id">
          <div className="wrap">
            <img
              className="img"
              src={`https://localhost:3000${item.imgSrc}`}
              alt=""
            />
          </div>
          <Flex className="content" direction="column" justify="between">
            <h3 className="item.title">{item.title}</h3>
            <Flex className="info" justify="between">
              <span>{item.form}</span>
              <span>{item.date}</span>
            </Flex>
          </Flex>
        </div>
      ))
    }
    
    render() {
      return (
        <div className="index">
          {/* 轮播图 */}
        <div className="swiper">
            <Carousel autoplay infinite autoplayInterval={5000}>
                    {this.renderSwipers()}
            </Carousel>
            {/* {this.state.isSwiperLoaded ? (
              <Carousel autoplay infinite autoplayInterval={5000}>
                {this.renderSwipers()}
              </Carousel>
            ) : (
              ''
            )} */}

            {/* 搜索框 */}
            <Flex className="search-box">
              {/* 左侧白色区域 */}
              <Flex className="search">
                {/* 位置 */}
                <div className="location" onClick={() => this.props.history.push('/citylist')}>
                  <span className="name">宜昌</span>
                  <i className="iconfont icon-arrow"></i>
                </div>
                {/* 搜索表单 */}
                <div className="form">
                  <i className="iconfont icon-seach"></i>
                  <span className="text">请输入小区或地址</span>
                </div>
              </Flex>
              {/* 右侧地图图标 */}
              <i className="iconfont icon-map" onClick={() => this.props.history.push('/map')}/>
            </Flex>
        </div>

          {/* 导航菜单 */}
          <Flex className="nav">
                {this.renderNavs()}
          </Flex>

          {/* 租房小组 */}
          <div className="group">
            <h3 className="group-title">
              <span>租房小组</span> <span className="more">更多</span>
            </h3>
            {/* 宫格组件 */}
            <Grid hasLine={false} square={false} data={data} columnNum="2" renderItem={(item) =>(
              <Flex className="group-item" justify="around">
                <div className="desc">
                  <p className="title">家住江南</p>
                  <span className="info">归属的感觉</span>
                </div>
                <img 
                src="https://gw.alipayobjects.com/zos/rmsportal/nywPmnTAvTmLusPxHPSu.png"
                alt=""
                />
              </Flex>
            )}/>
          </div>      

          {/* 最新资讯 */}
          <div className="news">
            <h3 className="group-title">最新咨询</h3>
            <WingBlank size="md">{this.renderNews()}</WingBlank>
          </div>   
        </div>
      );
    }
}